package com.jieshuibao.controller;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jieshuibao.common.config.Const;
import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.model.db.Drama;
import com.jieshuibao.model.db.User;
import com.jieshuibao.model.db.UserDrama;
import com.jieshuibao.model.db.Video;
import com.jieshuibao.model.domain.Article;
import com.jieshuibao.model.domain.ArticleCategory;
import com.jieshuibao.model.domain.ArticleDetailResponse;
import com.jieshuibao.model.domain.ArticleDiscussRequest;
import com.jieshuibao.model.domain.CookieUser;
import com.jieshuibao.model.domain.SearchResponse;
import com.jieshuibao.model.domain.UserLevel;
import com.jieshuibao.model.domain.VideoBuyRequest;
import com.jieshuibao.model.domain.VideoPayResponse;
import com.jieshuibao.model.domain.VideoReq;
import com.jieshuibao.model.domain.VideoRequest;
import com.jieshuibao.model.domain.VideoShareResponse;
import com.jieshuibao.service.DramaService;
import com.jieshuibao.service.PayVipBanlanceService;
import com.jieshuibao.service.RedisService;
import com.jieshuibao.service.UserDramaService;
import com.jieshuibao.service.UserService;
import com.jieshuibao.service.VideoService;
import com.jieshuibao.service.WeiXinPayService;
import com.jieshuibao.util.PayTypeUtil;
import com.jieshuibao.util.StringUtils;
import com.jieshuibao.util.UUIDGenerator;
import com.jieshuibao.wx.po.WxAppPayReq;
import com.jieshuibao.wx.po.WxAppPayRes;
import com.jieshuibao.wx.po.WxJsPayReq;
import com.jieshuibao.wx.po.WxjsPayRes;
import com.jieshuibao.wx.util.PayCommonUtil;

@Controller
@RequestMapping(value="/video")
public class VideoController {

	private static final Logger logger = LoggerFactory.getLogger("VideoController.class");
	private static final ObjectMapper mapper = new ObjectMapper();
	
	@Resource
	private RedisService redisService;
	@Resource
	private UserService userService;
	@Resource
	private DramaService dramaService;
	@Resource
	private UserDramaService userDramaService;
	@Resource
	private PayVipBanlanceService payVipBanlanceService;
	@Resource
	private WeiXinPayService weiXinPayService;
	@Resource
	private VideoService videoService;
	
	@RequestMapping(value = "/pay", method = RequestMethod.POST)
	@ResponseBody
	public Object queryWishList(HttpServletRequest request,@RequestBody VideoBuyRequest videoBuyRequest) {
		VideoPayResponse videoPayResponse = new VideoPayResponse();
		
		String videoId = videoBuyRequest.getVideoId();
		String payType = videoBuyRequest.getPayType();
		double money = videoBuyRequest.getMoney();
		int source = videoBuyRequest.getSource();
		String code = videoBuyRequest.getCode();
		
			CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
			if(cookieUser!=null){
				String phoneNumber = cookieUser.getPhoneNumber();
				User user = userService.getUserByPhoneNumber(phoneNumber);
				if(user!=null){
					System.out.println("videoId=="+videoId+","+"payType="+payType+","+"money="+money);
					if(videoId!=null&&!videoId.equals("")&&payType!=null&&!payType.equals("")&&money!=0.0){
						
						UserDrama userDrama = new UserDrama();
						String uuid = UUIDGenerator.getUUID();
						userDrama.setId(uuid);
						userDrama.setBuyTime(new Date());
						
						userDrama.setDramaId(videoId);
						userDrama.setMoney(money);
						Drama drama = dramaService.getDramaByUuid(videoId);
						if(drama!=null){
							Double price = drama.getPrice();
							if(price==money){
								userDrama.setUserId(phoneNumber);
								if(payType.equals("balance")){
									Double balance = user.getBalance();
									if(balance>=money){
										User user2 = new User();
										user2.setBalance(balance-money);
										user2.setPhoneNumber(phoneNumber);
										userDrama.setPayType(PayTypeUtil.PAYTYPE_BALANCE);
										userDrama.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
										userDramaService.addUserDramaAndUpdateUser(user2, userDrama);
										videoPayResponse.setCode("1");
									}else {
										//余额不足
										videoPayResponse.setCode("4");
										videoPayResponse.setDes("余额不足");
									}
								}else if(payType.equals("VipBalance")){
									int i = payVipBanlanceService.updateUserAndAddUserDrama(user, userDrama);
									if(i==1||i==2){
										//成功
										videoPayResponse.setCode("1");
									}else if(i==3){
										//数据错误
										videoPayResponse.setCode("3");
										videoPayResponse.setDes("数据错误");
									}else if(i==4){
										//余额不足
										videoPayResponse.setCode("4");
										videoPayResponse.setDes("会员卡余额不足");
									
									}else if(i==0){
										//系统繁忙
										videoPayResponse.setCode("0");
										videoPayResponse.setDes("系统繁忙");
									}
								}else if(payType.equals("weixin")){
									WxAppPayReq wxAppPayReq = new WxAppPayReq();
									wxAppPayReq.setPhone(phoneNumber);
								
									wxAppPayReq.setUnitPrice(money);
									wxAppPayReq.setProductName("购买视频");
									wxAppPayReq.setProductType(Const.VEDIO);
									wxAppPayReq.setProductId(uuid);
									userDrama.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);
									userDrama.setStatus(PayCommonUtil.PAYPENDING_STATUS);
									if(source==1){
										System.out.println("code"+code);
										WxJsPayReq req=new WxJsPayReq();
										req.setCode(code);
										req.setPhone(phoneNumber);
										
										req.setUnitPrice(money);
										req.setProductName("购买视频");
										req.setProductType(Const.VEDIO);
										req.setProductId(uuid);
										WxjsPayRes jssdPayRes=(WxjsPayRes)weiXinPayService.jSSDKPayInfo(req, request);
										userDramaService.addUserDrama(userDrama);
										System.out.println(jssdPayRes.toString());
										return jssdPayRes;
									}else {
										WxAppPayRes appPay = (WxAppPayRes) weiXinPayService
												.appPay(wxAppPayReq, request);
										userDramaService.addUserDrama(userDrama);
										return appPay;
									}
								}else {
									//支付类型错误
									videoPayResponse.setCode("3");
									videoPayResponse.setDes("请选择支付方式");
								}
							}else {
								//金额不对哦
								videoPayResponse.setCode("3");
								videoPayResponse.setDes("金额不对哦");
							}
						}else {
							//专辑id错误
							videoPayResponse.setCode("3");
							videoPayResponse.setDes("专辑id错误");
						}
						
					}else {
						//数据格式错误
						videoPayResponse.setCode("3");
						videoPayResponse.setDes("数据格式错误");
					}
					
				}else {
					//重新登录
					videoPayResponse.setCode("2");
					videoPayResponse.setDes("重新登录");
				}
			}else {
				//重新登录
				videoPayResponse.setCode("2");
				videoPayResponse.setDes("重新登录");
			}
		
		return videoPayResponse;
		
	}
	//视频购买
	@RequestMapping(value = "/buy", method = RequestMethod.POST)
	@ResponseBody
	public Object videoPay(HttpServletRequest request,@RequestBody VideoBuyRequest videoBuyRequest) {
		BaseRes<String> res = new BaseRes<String>();
		
		String videoId = videoBuyRequest.getVideoId();
		String payType = videoBuyRequest.getPayType();
		double money = videoBuyRequest.getMoney();
		int source = videoBuyRequest.getSource();
		String code = videoBuyRequest.getCode();
		CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
		String phoneNumber = cookieUser.getPhoneNumber();
		double balance = cookieUser.getBalance();
		Double vipBalance = cookieUser.getVipBalance();
		if (StringUtils.isNotBlank(videoId) && StringUtils.isNotBlank(payType) && money >0) {
			boolean buyVideo2 = videoService.isBuyVideo(phoneNumber, videoId);
			if (buyVideo2) {
				res.setCode(BaseRes.FAIL_CODE);
				res.setDes("已购买");
				return res;
			}
			String uuid = UUIDGenerator.getUUID();
			Video video = videoService.getVideoById(videoId);
			if (video != null) {
				Double price = video.getPrice();
				if (price==null||price<=0) {
					res.setCode(BaseRes.FAIL_CODE);
					res.setDes("视频免费");
					return res;
					
				}
				if (price == money) {
					if (payType.equals("balance")||payType.equals("VipBalance")) {
						if (payType.equals("balance")) {
							if (balance < money) {
								// 余额不足
								res.setCode(BaseRes.FAIL_CODE);
								res.setDes("余额不足");
								return res;
							}
						}else {
							if (money>vipBalance) {
								res.setCode(BaseRes.FAIL_CODE);
								res.setDes("顾问卡余额不足！");
								return res;
							}
						}
							boolean buyVideo = videoService.buyVideo(phoneNumber, uuid, payType, money, videoId);
							if (buyVideo) {
								res.setCode(BaseRes.SUCCESS_CODE);
								res.setDes(BaseRes.SUCCESS_DES);
								return res;
							}else {
								res.setCode(BaseRes.FAIL_CODE);
								res.setDes("支付失败");
								return res;
							}
					
					}  else if (payType.equals("weixin")) {
						WxAppPayReq wxAppPayReq = new WxAppPayReq();
						wxAppPayReq.setPhone(phoneNumber);
						wxAppPayReq.setUnitPrice(money);
						wxAppPayReq.setProductName("购买视频");
						wxAppPayReq.setProductType(PayTypeUtil.GOODSTYPE_VIDEO_SINGLE);
						wxAppPayReq.setProductId(uuid);
						if (source == 1) {
							WxJsPayReq req = new WxJsPayReq();
							req.setCode(code);
							req.setPhone(phoneNumber);
							req.setUnitPrice(money);
							req.setProductName("购买视频");
							req.setProductType(PayTypeUtil.GOODSTYPE_VIDEO_SINGLE);
							req.setProductId(uuid);
							WxjsPayRes jssdPayRes = (WxjsPayRes) weiXinPayService
									.jSSDKPayInfo(req, request);
							boolean buyVideo = videoService.buyVideo(phoneNumber, uuid, payType, money, videoId);
							if (buyVideo) {
								return jssdPayRes;
							}else {
								res.setCode(BaseRes.FAIL_CODE);
								res.setDes("支付失败");
								return res;
							}
							
						} else {
							boolean buyVideo = videoService.buyVideo(phoneNumber, uuid, payType, money, videoId);
							if (!buyVideo) {
								res.setCode(BaseRes.FAIL_CODE);
								res.setDes("支付失败");
								return res;
							}
							WxAppPayRes appPay = (WxAppPayRes) weiXinPayService
									.appPay(wxAppPayReq, request);
							return appPay;
						}
					} else {
						// 支付类型错误
						res.setCode(BaseRes.ERRORPARAM_CODE);
						res.setDes("请选择支付方式");
					}
				} else {
					// 金额不对哦
					res.setCode(BaseRes.ERRORPARAM_CODE);
					res.setDes("金额不对哦");
				}
			} else {
				// 专辑id错误
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes("视频id错误");
			}

		} else {
			// 数据格式错误
			res.setCode(BaseRes.ERRORPARAM_CODE);
			res.setDes("数据格式错误");
		}
		
		return res;
		
	}
	/**
	 * 大咖访谈/根据标题查询视频/微课（单个）搜索
	 * @param request
	 * @param searchResponse
	 * @return
	 */
	@RequestMapping(value = "/search", method = RequestMethod.POST)
	@ResponseBody
	public Object searchVideo(HttpServletRequest request,@RequestBody VideoRequest videoRequest) {
		SearchResponse searchResponse = new SearchResponse();

		try {
			logger.info("接收：" + mapper.writeValueAsString(videoRequest));
			
			//获取用户信息
			CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
			//获取手机号码
			String phoneNumber = cookieUser.getPhoneNumber();
			//用户手机号码不存在时，重新登录
			if(phoneNumber == null || "".equals(phoneNumber)){
				searchResponse.setCode("2");
				searchResponse.setDes("重新登录");
				return searchResponse;
			}
			//数据起始索引
			int sinceId = videoRequest.getSinceId();
			//数据结束索引
			int maxId = videoRequest.getMaxId();
			//数据索引-逻辑处理
			if(sinceId <= 0) {
				sinceId = 1;
			}
			if(maxId <= 0 || maxId < sinceId){
				maxId = sinceId;
			}
			//文章标题
			String videoTitle = videoRequest.getTitle();
			//税种ID
			String tax = videoRequest.getTax();
			//专题ID
			String topic = videoRequest.getTopic();
			//行业ID
			String trade = videoRequest.getTrade();
			//视频类别
			String type = videoRequest.getType();
			if(type == null || (!"0".equals(type) && !"3".equals(type))){
				searchResponse.setCode("3");
				searchResponse.setDes("数据格式错误");
				return searchResponse;
			}
			
			Map<String, Object> searchMap = new HashMap<String, Object>();
			searchMap.put("pageIndex", sinceId - 1);
			searchMap.put("pageSize", maxId - sinceId + 1);
			searchMap.put("type", type);
			searchMap.put("phoneNumber", phoneNumber);
			if(videoTitle != null && !"".equals(videoTitle)){
				searchMap.put("title", videoTitle);
			}
			if(tax != null && !"".equals(tax)){
				searchMap.put("tax", tax);
			}
			if(topic != null && !"".equals(topic)){
				searchMap.put("topic", topic);
			}
			if(trade != null && !"".equals(trade)){
				searchMap.put("trade", trade);
			}
			List<Map<String, Object>> videos = videoService.selectBySearchMap(searchMap);
			searchResponse.setVideos(videos);
			searchResponse.setCode("1");
			searchResponse.setSinceId(sinceId);
			searchResponse.setMaxId(maxId);
			searchResponse.setRows(videos.size());
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return searchResponse;
	}
	
	
	// 视频-分享
		@RequestMapping(value = "/videoDetail/share", method = RequestMethod.POST)
		@ResponseBody
		public Object vedioShare(HttpServletRequest request,
				@RequestBody VideoReq videoRequest) {
			VideoShareResponse videoShareResponse = new VideoShareResponse();
			try {
				logger.info("接收：" + mapper.writeValueAsString(videoRequest));
				//获取视频ID
				String videoId = videoRequest.getId();
				if (videoId != null && !videoId.equals("")) {
					//获取视频数据
					Video video = videoService.getVideoById(videoId);
					//标题titile、封面image、视频播放ID  vid(是否收费，收费为null)
					if (video != null) {
						//获取标题
						String title = video.getTitle();
						//获取封面
						String image = video.getImage();
						//获取价格
						Double price = video.getPrice();
						//判断是否免费
						if(price == 0){
							videoShareResponse.setVid(video.getVid());
						}else{
							videoShareResponse.setVid(null);
						}
						videoShareResponse.setImage(image);
						videoShareResponse.setTitle(title);
						videoShareResponse.setCode(BaseRes.SUCCESS_CODE);
						videoShareResponse.setDes(BaseRes.SUCCESS_DES);
					} else {
						//参数不正确
						videoShareResponse.setCode(BaseRes.ERRORPARAM_CODE);
						videoShareResponse.setDes(BaseRes.ERRORPARAM_DES);
					}
				} else {
					// 参数不正确
					videoShareResponse.setCode(BaseRes.ERRORPARAM_CODE);
					videoShareResponse.setDes(BaseRes.ERRORPARAM_DES);
				}
				logger.debug("返回：" + mapper.writeValueAsString(videoShareResponse));
			} catch (Exception e) {
				e.printStackTrace();
				videoShareResponse.setCode(BaseRes.FAIL_CODE);
				videoShareResponse.setDes(BaseRes.FAIL_DES);
			}
			return videoShareResponse;
		}

}
